#include "licensemanager.h"
#include <QSettings>
#include <QCryptographicHash>
#include <QSysInfo>

LicenseManager& LicenseManager::instance()
{
    static LicenseManager instance;
    return instance;
}

LicenseManager::LicenseManager()
    : m_isActivated(false)
{
    m_hardwareId = generateHardwareId();
    loadActivation();
}

LicenseManager::~LicenseManager()
{
}

bool LicenseManager::isLicensed() const
{
    return m_isActivated;
}

bool LicenseManager::checkDeviceLimit()
{
    // TODO: 实现设备数量检查
    return true;
}

QString LicenseManager::generateHardwareId() const
{
    QString systemInfo = QSysInfo::machineUniqueId() + 
                        QSysInfo::machineHostName() +
                        QSysInfo::currentCpuArchitecture();
    
    return QCryptographicHash::hash(systemInfo.toUtf8(), 
                                  QCryptographicHash::Sha256).toHex();
}

bool LicenseManager::verifyWithServer(const QString& licenseKey)
{
    // TODO: 实现服务器验证
    return false;
}

void LicenseManager::saveActivation()
{
    QSettings settings;
    settings.setValue("License/Key", m_licenseKey);
    settings.setValue("License/HardwareId", m_hardwareId);
}

bool LicenseManager::loadActivation()
{
    QSettings settings;
    m_licenseKey = settings.value("License/Key").toString();
    QString savedHardwareId = settings.value("License/HardwareId").toString();
    
    if (!m_licenseKey.isEmpty() && savedHardwareId == m_hardwareId) {
        m_isActivated = verifyWithServer(m_licenseKey);
    }
    
    return m_isActivated;
}

bool LicenseManager::activateLicense(const QString& licenseKey)
{
    // TODO: 实现真实的授权验证逻辑
    m_licenseKey = licenseKey;
    m_isActivated = verifyWithServer(licenseKey);
    if (m_isActivated) {
        saveActivation();
    }
    return m_isActivated;
}

QString LicenseManager::getHardwareId() const
{
    return m_hardwareId;
} 